package com.aloda.ojsandbox.sandbox;

import com.aloda.ojsandbox.anno.SandboxStrategyConfig;
import com.aloda.ojsandbox.pojo.dto.ExecuteCodeRequest;
import com.aloda.ojsandbox.pojo.dto.ExecuteCodeResponse;
import com.aloda.ojsandbox.pojo.enums.CodeSandboxLanguageEnum;
import com.aloda.ojsandbox.pojo.enums.ResponseEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 代码沙箱策略执行器
 *
 * @Author aloda
 * @Date 2025/5/1 14:15
 */
@Service
public class SandboxStrategyExecutor {

    // 代码沙箱策略策略列表
    @Resource
    private List<CodeSandbox> codeSandboxList;

    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        String language = executeCodeRequest.getLanguage();
        CodeSandboxLanguageEnum languageEnum = CodeSandboxLanguageEnum.getEnumByText(language);
        if (language == null) {
            return ExecuteCodeResponse.error(ResponseEnum.PARAM_ERROR.getStatus(), "语言参数传递错误");
        }
        for (CodeSandbox codeSandbox : codeSandboxList) {
            if (codeSandbox.getClass().isAnnotationPresent(SandboxStrategyConfig.class)) {
                SandboxStrategyConfig sandboxStrategyConfig = codeSandbox.getClass().getAnnotation(SandboxStrategyConfig.class);
                if (sandboxStrategyConfig.sandboxLanguageType() == languageEnum) {
                    return codeSandbox.executeCode(executeCodeRequest);
                }
            }
        }
        return ExecuteCodeResponse.error(ResponseEnum.FAILURE.getStatus(), "未找到语言对应的代码沙箱");
    }
}
